<template>
    <view class="xilu">
        <!--  -->
        <view class="page-foot bg-white">
            <view class="flex-box tc fs24 col5">
                <view class="share_btn" @tap="sharePop = true">
                    <image src="../../static/icon/detail_share.png" mode="aspectFill" class="xilu_share"></image>
                    <view class="fs24 col5">分享</view>
                </view>
                <view class="share_btn" @click="togglesCollect()">
                    <image src="../../static/icon/detail_collect-on.png" v-if="product.is_collection_count" mode="aspectFill" class="xilu_share"></image>
                    <image src="../../static/icon/detail_collect.png" v-else mode="aspectFill" class="xilu_share"></image>
                    <view>收藏</view>
                </view>
                <!-- <view class="btn1" @click="bindAddProduct">卖同款</view> -->
                <view class="btn2" @click="bindWantProduct">立即沟通</view>
            </view>
        </view>
        <!--  -->
        <view class="container">
            <!--  -->
            <swiper class="xilu_banner" autoplay circular>
                <swiper-item v-for="(item,index) in product.images_text">
                    <image :src="item" mode="aspectFill"></image>
                </swiper-item>
            </swiper>
            <!--  -->
            <view class="p30 xilu_title fs34 fwb">{{product.name}}</view>
            <view class="plr30 pb30 pb50 flex-box flex-between">
                <view class="red fs40 fwb"><text class="fs24">¥</text>{{product.salesprice}}</view>
                <view class="fs24 col89">{{product.want_num}}人想要</view>
            </view>
            <!--  -->
            <view class="flex-box plr30 pb50">
                <image class="xilu_avatar mr20" :src="product.user.avatar" @click="bindHome()" mode="aspectFill"></image>
                <view class="flex-grow-1">
                    <view class="fs32 pb15 blue">{{product.user.nickname}}</view>
                    <view class="fs24 col89">{{product.user.logintime_text}} </view>
                </view>
                <view class="btn1 fs24" @click="toggleFocus()">{{product.is_focus_count?'已关注':'+ 关注'}}</view>
            </view>
            <!--  -->
            <view class="plr30 pb50">
                <view class="fs34 col10 fwb pb20">商品描述</view>
                <!-- 富文本 -->
                <u-parse :content="product.content"></u-parse>
            </view>
        </view>
        <canvas style="width: 650px;height: 770px;position: fixed;top: -999em;right: -999em;" canvas-id="myCanvas" id="myCanvas1"></canvas>
        <u-popup :show="sharePop" mode="bottom" round="20" closeOnClickOverlay closeable @cancel="sharePop = false" @close="sharePop = false">
            <view class="bottom_pop">
                <view class="pb50 tc fs34 col3">分享</view>
                <view class="flex-box flex-around">
                    <button hover-class="none" open-type="share">
                        <image src="/static/icon/share1.png" mode="aspectFill" class="icon_share"></image>
                        <view>微信</view>
                    </button>
                    <button hover-class="none">
                        <image src="/static/icon/share2.png" mode="aspectFill" class="icon_share"></image>
                        <view>朋友圈</view>
                    </button>
                    <button hover-class="none" @tap.stop="showCanvas">
                        <image src="/static/icon/share3.png" mode="aspectFill" class="icon_share"></image>
                        <view>海报</view>
                    </button>
                </view>
            </view>
        </u-popup>
        <u-popup :show="canvasPop" mode="center" round="20" closeOnClickOverlay @cancel="canvasPop = false" @close="canvasPop = false" customStyle="background:transparent;">
            <image :src="imgPath" style="width: 650rpx;height: 770rpx;display: block;border-radius: 30rpx;"></image>
            <!-- <image src="/static/icon/close.png" class="close" mode="aspectFill" @tap.stop="canvasPop = false"></image> -->
            <view class="flex-box flex-center">
                <view class="btns btn1" @tap.stop="canvasPop = false">取消</view>
                <view class="btns btn2">保存图片</view>
            </view>
        </u-popup>
        <u-popup :show="msgPop" mode="bottom" round="20" closeOnClickOverlay closeable @cancel="msgPop = false" @close="msgPop = false">
            <view class="ptb50 tc fs34 col3">留言记录</view>
            <view class="msg_pop">
                <mescroll-uni @init="mescrollInit" @down="downCallback" @up="upCallback" :fixed="false">
                    <view class="xilu_leave_word" v-for="(item,index) in forumComments" :key="index">
                        <view class="flex-box flex-align-start ptb30">
                            <image class="xilu_avatar mr30" :src="item.user.avatar" mode="aspectFill"></image>
                            <view class="flex-grow-1">
                                <view class="flex-box flex-between pb10">
                                    <view class="fs30 blue">{{item.user.nickname}}</view>
                                    <view class="fs24 col89">{{item.createtime_text}}</view>
                                </view>
                                <view class="fs30 col10" @click="bindApply(index)">{{item.content}}</view>
                            </view>
                        </view>
                        <view class="xilu_reply flex-box ptb30 mb30 flex-align-start" v-if="!item.childCommentsMore.nothing" v-for="(item2,index2) in item.childComments">
                            <image class="xilu_avatar mr15" :src="item2.user.avatar" mode="aspectFill"></image>
                            <view class="flex-grow-1">
                                <view class="flex-box flex-between pb10">
                                    <view class="fs30 blue">{{item2.user.nickname}}</view>
                                    <view class="fs24 col89">{{item2.createtime_text}}</view>
                                </view>
                                <view class="fs30 col10">{{item2.content}}</view>
                            </view>
                        </view>
                        <view class="flex-box flex-center ptb30" v-if="item.childlist_count>0">
                            <view class="m-arrow-down" @click="fetchSecondComments(index)" v-if="item.childCommentsMore.page==1"><text class="pr10">展开{{item.childlist_count}}评论</text></view>
                            <view class="m-arrow-down" @click="fetchSecondComments(index)" v-else-if="item.childCommentsMore.page>1 && !item.childCommentsMore.nomore"><text class="pr10">加载更多</text></view>
                            <view class="m-arrow-up ml30" v-if="item.childCommentsMore.page>1" @click="bindRetract(index)"><text class="pr10">收起</text></view>
                        </view>
                    </view>
                </mescroll-uni>
            </view>
        </u-popup>
    </view>
</template>

<script>
    import canvas from '@/xilu/canvas.js'
    // 引入mescroll-mixins.js
    import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";
    export default {
        mixins: [MescrollMixin], // 使用mixin
        data() {
            return {
                productId: 0,
                product: {
                    name: '',
                    category_id: '',
                    content: '',
                    images: '',
                    salesprice: '0.00',
                    freight_status: '',
                    freight_money: '0.00',
                    createtime_text: '',
                    want_num: 0,
                    user: {
                        id: '',
                        nickname: '',
                        avatar: '',
						logintime_text:''
                    }
                },
                messageList: [],
                messageListMore: {
                    page: 1
                },
                sharePop: false, //分享弹窗
                canvasPop: false, //海报弹窗

                goodsImg1: {}, // 商品图信息1
                goodsImg2: {}, // 商品图信息2
                ewmImg: {}, // 二维码图片信息
                avatarImg: {}, // 头像信息
                isShow: false, //显示保存按钮
                imgPath: "", //生成的图片路径
                msgPop: false, //留言弹窗
            }
        },
        onLoad(options) {
            this.productId = options.id || 0;
            this.fetchDetail();
            this.fetchMessage();
        },
		onShareAppMessage(e) {
			const promise = new Promise(resolve => {
			  setTimeout(() => {
				resolve({
				  title: this.product.name
				})
			  }, 2000)
			})
			return {
			  title: this.product.name,
			  path: '/pages/recovery_detail/recovery_detail?id='+this.product.id,
			  imageUrl: this.product.images_text.length>0?this.product.images_text[0]:'',
			  promise 
			}
		},
		onShareTimeline(){
			const promise = new Promise(resolve => {
			  setTimeout(() => {
				resolve({
				  title: this.product.name
				})
			  }, 2000)
			})
			return {
			  title: this.product.name,
			  path: '/pages/recovery_detail/recovery_detail?id='+this.product.id,
			  imageUrl: this.product.images_text.length>0?this.product.images_text[0]:'',
			  promise 
			}
		},
        methods: {
			//详情
			fetchDetail() {
			    this.$core.get({url: 'xilumarket.product/detail',data: {product_id: this.productId},success: ret => {
			            this.product = ret.data
			        },
			        fail: err => {
			            console.log(err);
			        }
			    });
			},
            showCanvas() {
				if(!this.$core.getUserinfo(true)){
					return '';
				}
				this.$core.get({url: 'xilumarket.product/poster_info',data: {product_id: this.productId},success: ret => {
			            this.loadCavas(ret.data);
			        },
			        fail: err => {
			            console.log(err);
			        }
			    })
            },
            async loadCavas() {
                let that = this;

                // 获取背景图，二维码信息等，APP端会返回图片的本地路径（H5端只能返回原路径）
                let goodsImgUrl = '/static/images/goods.png'; // 主图本地路径，也可以用网络地址
                let ewmImgUrl = '/static/images/goods.png';
                let avatarImgUrl = '/static/icon/goods.png';
                that.goodsImg = await that.getImageInfo(goodsImgUrl);
                that.ewmImg = await that.getImageInfo(ewmImgUrl);
                that.avatarImg = await that.getImageInfo(avatarImgUrl);

                // 如果主图，二维码图片，设备信息都获取成功，开始绘制海报，这里需要用setTimeout延时绘制，否则可能会出现图片不显示。
                if (that.goodsImg.errMsg == 'getImageInfo:ok' && that.ewmImg.errMsg == 'getImageInfo:ok' && that.avatarImg.errMsg == 'getImageInfo:ok') {
                    console.log('读取图片信息成功')
                    uni.showToast({
                        icon: 'loading',
                        mask: true,
                        duration: 10000,
                        title: '海报绘制中',
                    });
                   setTimeout(() => {
                       // 获取canvas上下文
                       var ctx = uni.createCanvasContext('myCanvas', that);
                       // 1.填充背景色，白色
                       ctx.setFillStyle('#fff'); // 默认白色
                       ctx.fillRect(0, 0, 650, 1064) // fillRect(x,y,宽度，高度)
                
                       // 2. 绘制头像，昵称
                       canvas.clipCircleImg(ctx, 30, 30, 25, that.avatarImg.path);
                       canvas.fillTextCut(ctx, '哇哇的二手闲置', 32, 32, 100, 39, 550, 1, false, "#333");
                   
                       // 3.绘制商品图
                       ctx.drawImage(that.goodsImg.path, 30, 110, 590, 590); // drawImage(图片路径,x,y,绘制图像的宽度，绘制图像的高度)
                   
                       // 4.绘制白色矩形
                       canvas.clipRoundRect(ctx, 0, 912, 650, 152, 0, '#FFC100');
                   
                       // 5.绘制昵称，提示语
                       canvas.fillTextCut(ctx, '二手闲置', 34, 34, 30, 947, 308, 1, false, "#101010");
                       canvas.fillTextCut(ctx, '让你的闲置找到更多价值', 28, 28, 30, 1001, 308, 1, false, "#616161");
                   
                       // 6.绘制二维码
                       ctx.drawImage(that.ewmImg.path, 520, 938, 100, 100); // drawImage(图片路径,x,y,绘制图像的宽度，绘制图像的高度)
                   
                       // 7.绘制简介
                       canvas.fillTextCut(ctx, '宜家单人小沙发 可拆卸 套子可清洗宜家单人小沙发 可拆卸 套子可清洗', 34, 44, 30, 730, 590, 2, false, "#101010");
                   
                       // 7.绘制现价
                       canvas.fillTextCut(ctx, '¥150.00', 34, 34, 30, 847, 140, 1, false, "#FE3846");
                   
                       // 8.绘制原价
                       canvas.fillTextCut(ctx, '原价¥320', 24, 24, 170, 850.5, 140, 1, false, "#898989");
                       canvas.clipRoundRect(ctx, 170, 859, 120, 1, 0, '#898989');
                   
                       // 8.绘制想要
                       canvas.fillTextCut(ctx, '128人想要', 24, 24, 509, 853, 111, 1, false, "#898989");
                   
                       // draw方法 把以上内容画到 canvas 中
                       ctx.draw(true, (ret) => {
                           that.isShow = true // 显示按钮-保存图片到相册
                   
                           uni.showToast({
                               icon: 'success',
                               mask: true,
                               title: '绘制完成',
                           });
                           uni.canvasToTempFilePath({ // 保存canvas为图片
                               canvasId: 'myCanvas',
                               quality: 1,
                               complete: function(res) {
                                   // 在H5平台下，tempFilePath 为 base64, // 图片提示跨域 H5保存base64失败，APP端正常输出临时路径
                                   that.imgPath = res.tempFilePath;
                                   uni.setStorageSync('filePath', res.tempFilePath); //保存临时文件路径到缓存
                                   that.canvasPop = true;
                                   that.sharePop = false;
                               },
                           })
                       });
                   }, 1500)

                } else {
                    console.log('读取图片信息失败');
                }
            },
            // 获取图片信息
            getImageInfo(image) {
                return new Promise((req, rej) => {
                    uni.getImageInfo({
                        src: image,
                        success: function(res) {
                            req(res)
                        },
                    });
                })
            },
            // 保存图片到相册
            saveImage() {
                let imgPath = this.imgPath
                uni.saveImageToPhotosAlbum({
                    filePath: imgPath,
                    success(res) {
                        uni.showToast({
                            icon: 'success',
                            mask: true,
                            title: '保存成功',
                        });
                    },
                    fail(res) {
                        console.log(res.errMsg)
                    }
                })
            },
            
            //留言
            fetchMessage() {
                this.$util.fetch(this, 'xilumarket.product_message/lists', {
                    product_id: this.productId,
                    pagesize: 10
                }, 'messageListMore', 'messageList', 'data', data => {

                })
            },
            // 关注取关
            toggleFocus() {
                if (!this.$core.getUserinfo(true)) {
                    return true;
                }
                this.$core.post({
                    url: 'xilumarket.forum/toggle_focus',
                    data: {
                        user_id: this.product.user_id
                    },
                    success: ret => {
                        this.product.is_focus_count = ret.data.is_focus_count;
                        this.$forceUpdate();
                    },
                    fail: err => {
                        console.log(err);
                    }
                });
            },
            // 点击收藏
            togglesCollect() {
                this.$core.post({
                    url: 'xilumarket.product/toggle_collection',
                    data: {
                        product_id: this.product.id
                    },
                    success: ret => {
                        this.product.is_collection_count = ret.data.is_collection_count;
                        this.$forceUpdate();
                    },
                    fail: err => {}
                });
            },
            bindAddProduct() {
                if (!this.$core.getUserinfo(true)) {
                    return ''
                }
                let product = {
                    name: this.product.name,
                    category_id: this.product.category_id,
                    content: this.product.content,
                    images: this.product.images_text,
                    salesprice: this.product.salesprice,
                    freight_status: this.product.freight_status,
                    freight_money: this.product.freight_money
                }
                uni.navigateTo({
                    url: '/pages/public_xianzhi/public_xianzhi',
                    success(res) {
                        res.eventChannel.emit('addProductTransfor', product)
                    }
                })
            },
            //我想要
            bindWantProduct() {
                if (!this.$core.getUserinfo(true)) {
                    return ''
                }
				console.log(getApp().globalData.chat_config.SocketTask)
				if(!getApp().globalData.chat_config.SocketTask){
					uni.showToast({
						title: '即时通过未开启',
						icon:'none'
					})
					return false;
				}
                let product = {
					id: this.product.id,
                    name: this.product.name,
                    want_num: this.product.want_num,
                    thumb_image_text: this.product.thumb_image_text,
                    salesprice: this.product.salesprice,
                    freight_status: this.product.freight_status,
                    freight_money: this.product.freight_money,
					to_username: this.product.user?this.product.user.nickname:''
                }
                uni.navigateTo({
                    url: '/pages/chat/chat?receive_user_id='+this.product.user_id+'&product_id='+this.product.id,
                    success(res) {
                        res.eventChannel.emit('chatProductTransfor', product)
                    }
                })
            },
			bindHome() {
			    uni.navigateTo({
			        url: '/pages/home_page/home_page?id=' + this.product.user_id + '&tab=product'
			    })
			}
        }
    }
</script>

<style lang="scss" scoped>
    .xilu {
        &_banner {
            width: 750rpx;
            height: 750rpx;

            image {
                width: 750rpx;
                height: 750rpx;
            }
        }

        &_title {
            color: #101010;
            line-height: 48rpx;
        }

        &_avatar {
            width: 80rpx;
            height: 80rpx;
            border-radius: 50%;
        }

        .btn1 {
            height: 54rpx;
            line-height: 54rpx;
            width: 110rpx;
        }

        &_share {
            width: 45rpx;
            height: 45rpx;
        }

        .share_btn {
            line-height: 1;
            padding: 0;
            margin: 0;
            border: none;
            padding-right: 30rpx;
            padding-left: 10rpx;

            image {
                margin-bottom: 8rpx;
            }

            &::after {
                border: none;
            }
        }

        .page-foot {
            .flex-box {
                padding: 10rpx 30rpx;

                .share_btn:first-child {
                    padding-left: 0;
                }
            }

            .btn1,
            .btn2 {
                width: 160rpx;
                height: 80rpx;
                line-height: 78rpx;
                font-size: 30rpx;
                color: #101010;
            }

            .btn2 {
                margin-left: auto;
                margin-right: 20rpx;
            }
        }

        .icon_share {
            width: 90rpx;
            height: 90rpx;
            margin-bottom: 20rpx;
            border-radius: 50%;
        }

        .close {
            width: 48rpx;
            height: 48rpx;
            display: block;
            margin: 40rpx auto 0;
        }

        &_leave_word {
            border-bottom: 1px solid #eee;
        }

        &_reply {
            padding: 30rpx;
            background: #F7F9FC;
            border-radius: 15rpx;
        }

        .msg_pop {
            width: 100%;
            padding: 0 30rpx;
            max-height: 80vh;
            overflow-y: scroll;
        }

        .btns {
            width: 250rpx;
            height: 90rpx;
            line-height: 90rpx;
            border: none;
            margin: 60rpx 20rpx 0;
        }

        .btns.btn1 {
            background: #E5E5E5;
        }

        .btns.btn2 {
            background: #FFC100;
        }
    }
</style>